package com.treasure.mall.biz.service.core.pay.impl;

import com.treasure.mall.biz.base.AbstractSearchableCrudService;
import com.treasure.mall.biz.base.SpecificationAndSort;
import com.treasure.mall.biz.dto.BaseSaveDTO;
import com.treasure.mall.biz.dto.BaseSearchDTO;
import com.treasure.mall.biz.dto.condition.PaymentBillCondition;
import com.treasure.mall.biz.dto.pay.PaymentBillSaveDTO;
import com.treasure.mall.biz.entity.pay.PaymentBillPO;
import com.treasure.mall.biz.entity.pay.PaymentBillPO_;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.entity.user.UserPO_;
import com.treasure.mall.biz.repository.pay.PaymentRepository;
import com.treasure.mall.biz.service.core.pay.PaymentBillService;
import com.treasure.mall.zbq.common.Jsr310Utils;
import com.treasure.mall.zbq.common.RandomUtils;
import com.treasure.mall.zbq.common.ienum.order.OrderEnums;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/6/14
 */
@Service
public class PaymentBillServiceImpl extends AbstractSearchableCrudService<PaymentBillPO, String> implements PaymentBillService {
    private PaymentRepository paymentRepository;

    @Autowired
    protected PaymentBillServiceImpl(PaymentRepository repository) {
        super(repository);
        this.paymentRepository = repository;
    }

    @Override
    protected SpecificationAndSort<PaymentBillPO> specificationAndSort(BaseSearchDTO searchDTO) {
        PaymentBillCondition condition = (PaymentBillCondition) searchDTO;

        Specification<PaymentBillPO> specification = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (!StringUtils.isEmpty(condition.getUserKey())) {
                predicates.add(cb.or(
                        cb.like(root.get(PaymentBillPO_.payer).get(UserPO_.mobile), likeAll(condition.getUserKey())),
                        cb.like(root.get(PaymentBillPO_.payer).get(UserPO_.realName), likeAll(condition.getUserKey()))
                ));
            }

            if (!StringUtils.isEmpty(condition.getBillId())) {
                predicates.add(cb.equal(root.get(PaymentBillPO_.id), condition.getBillId()));
            }

            if (!StringUtils.isEmpty(condition.getBeginTime())) {
                LocalDateTime beginTime = Jsr310Utils.DateTime.of(condition.getBeginTime());
                predicates.add(cb.greaterThanOrEqualTo(root.get(PaymentBillPO_.createTime), beginTime));
            }
            if (!StringUtils.isEmpty(condition.getEndTime())) {
                LocalDateTime endTime = Jsr310Utils.DateTime.of(condition.getEndTime());
                predicates.add(cb.lessThanOrEqualTo(root.get(PaymentBillPO_.createTime), endTime));
            }
            if (!StringUtils.isEmpty(condition.getOrderId())) {
                predicates.add(cb.equal(root.get(PaymentBillPO_.orderId), condition.getOrderId()));
            }

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        Sort sort = new Sort(Sort.Direction.DESC, "createTime");

        return new SpecificationAndSort<>(specification, sort);
    }

    @Override
    @Transactional
    public PaymentBillPO save(BaseSaveDTO saveDTO) {
        PaymentBillSaveDTO billSaveDTO = (PaymentBillSaveDTO) saveDTO;
        PaymentBillPO paymentBillPO = new PaymentBillPO();
        paymentBillPO.setId(RandomUtils.randomFlowNo());
        paymentBillPO.setOrderId(billSaveDTO.getOrderId());
        paymentBillPO.setPayer(new UserPO(billSaveDTO.getUserId()));
        paymentBillPO.setPayTime(LocalDateTime.now());
        paymentBillPO.setPayType(billSaveDTO.getPayType());
        paymentBillPO.setAmount(billSaveDTO.getAmount());
        paymentBillPO.setDealType(billSaveDTO.getDealType());
        paymentBillPO.setPayStatus(OrderEnums.PayStatus.TO_PAY);
        paymentBillPO.setOpenId(billSaveDTO.getOpenId());
        paymentBillPO.setThirdPay(billSaveDTO.isThirdPay());
        paymentBillPO.setAuctionSessionId(billSaveDTO.getAuctionSessionId());

        return repository.save(paymentBillPO);
    }

    @Override
    public List<PaymentBillPO> findByOrder(String orderId) {
        return paymentRepository.findByOrderId(orderId);
    }

    @Override
    public PaymentBillPO getThirdPayBill(String orderId) {
        return paymentRepository.findByOrderIdAndThirdPayIsTrue(orderId);
    }

    @Override
    public List<PaymentBillPO> getUserPayBill(String orderId) {
        return paymentRepository.findByOrderIdAndThirdPayIsFalse(orderId);
    }

    @Override
    public PaymentBillPO getBalancePayBill(String orderId) {
        return paymentRepository.findByOrderIdAndPayType(orderId, OrderEnums.PayType.BALANCE_PAY);
    }
}
